#include <iostream>
#include <cerrno>
#include <cstring>
#include <string>
#include <unistd.h>
#include <sys/types.h> 
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "InetAddr.hpp"
#include "mythread.hpp"
#include "Comm.hpp"
#include"Log.hpp"

void Usage(const char* proc)
{
    std::cout << "Usage : \n\t" << proc << " server_ip server_port\n" << std::endl;
}


class ThreadData
{
public:
    ThreadData(int sock, struct sockaddr_in &server) : _sockfd(sock), _serveraddr(server)
    {
    }
    ~ThreadData()
    {
    }

public:
    int _sockfd;
    InetAddr _serveraddr;
};

void RecverRoutine(ThreadData& td)
{
    char buffer[1024];
    while(true)
    {
        //收消息
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        ssize_t m = recvfrom(td._sockfd, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&temp, &len); // 一般建议都是要填的.
        if(m > 0)
        {
            buffer[m] = 0;
            std::cerr << buffer << std::endl;
        }
        else
            break;
    }
}

//该线程用于发消息
void SenderRoutine(ThreadData& td)
{
    while(true)
    {
        //要发送的数据
        std::string inbuffer;
        std::cout << "Please Enter# ";
        getline(std::cin,inbuffer);
        //发送给server
        auto server = td._serveraddr.GetAddr();
        ssize_t n = sendto(td._sockfd, inbuffer.c_str(), inbuffer.size(), 0, (struct sockaddr*)&server, sizeof(server));
        if (n <= 0)
            std::cout << "send error" << std::endl;
    }
}

// ./udp_client server_ip server_port
int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        return Usage_Err;
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    //创建socket
    int sock = socket(AF_INET,SOCK_DGRAM,0);
    if(sock < 0)
    {
        lg.LogMessage(Fatal, "socket errr, %d : %s\n", errno, strerror(errno));
        exit(Socket_Err);
    } 
    std::cout << "create socket success: " << sock << std::endl;

    //client需要进行绑定，但我们不显示绑定，而是第一次发生时让系统自动随机绑定
    //填充server信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());


    //创建两个线程，一个用于发，一个用于收，实现收发的分离
    ThreadData td(sock,server);
    Thread<ThreadData> recver("recver", RecverRoutine, td);
    Thread<ThreadData> sender("sender", SenderRoutine, td);

    recver.Start();
    sender.Start();

    recver.join();
    sender.join();

    close(sock);
    return 0;
}